package cn.huugh.number.cn.hugh.netutil;

import jdk.management.resource.internal.inst.SocketOutputStreamRMHooks;

import java.io.*;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ConnectedSocket extends SocketEvent{
    private Socket socket;
    MessageHandler messageHandler;
    public static boolean keepAlive = true;
    private final ExecutorService es = Executors.newFixedThreadPool(10);
    public ConnectedSocket(Socket socket,MessageHandler messageHandler){//构造方法
        this.socket = socket;
        this.messageHandler = messageHandler;
        if(socket!=null){
            new Thread(() -> {//lambda表达式创建线程
                messageHandler.onClientConnected(this);
                try {
                    BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
                    while (true) {
                        String message = br.readLine();
                        messageHandler.onMessageReceive(this, message);
                    }
                } catch (IOException e) {
                    disConnect();
                }
            }).start();
        }

    }
    public void keepAlive(long delay){//发送心跳包
        while(keepAlive) {
            es.execute(()->{
                try {
                    Thread.sleep(delay);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                sendMessage(0);
            });
        }
    }
    public void sendMessage(Object message){//发送消息
            try {
                BufferedWriter bw = new BufferedWriter(new OutputStreamWriter
                        (socket.getOutputStream(), "UTF-8"));//获取输出流
                bw.write(message + "\n");//写入信息
                bw.flush();//刷新流
                //bw.close();
            }
         catch (IOException ignored) { }
    }
    public void sendMessage(byte[] message){//发送消息
        try {
            OutputStream bos = socket.getOutputStream();
            bos.write(message);
            bos.flush();//刷新流
            //bw.close();
        }
        catch (IOException ignored) { }
    }
    public void disConnect(){//断开Socket连接
        try { socket.close(); } catch (IOException ignored) { }
        messageHandler.onClientDisconnected(this);
    }
    public Socket getSocket(){//获取当前Socekt对象
        if(socket.isConnected()){
            return this.socket;
        }else{
            throw new RuntimeException("Socket连接断开，无法获取Socket");
        }

    }
}